package ru.averta.notes.domain.abstr;


import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;

import ru.averta.notes.domain.User;
import ru.averta.notes.domain.flags.IUserable;
import ru.averta.notes.exceptions.CannotChangeUserException;
import ru.averta.notes.exceptions.UnspecifiedUserException;
import ru.averta.notes.exceptions.WrongUserableUserException;

@MappedSuperclass
public abstract class UserableObject extends AbstractPersistentObject implements IUserable {

	@ManyToOne(fetch=FetchType.EAGER)
	@JoinColumn(name="USER_ID", nullable=false)
	User user;

	public void setUser(User newUser) {
		if (newUser != null) {
			if (user == null) {
				user = newUser;
			} else if (!user.equals(newUser)) {
				throw new CannotChangeUserException(user, newUser);
			}
		}
	}

	public User getUser() {
		return user;
	}

	public boolean isAddUserable(IUserable object) {
		if (object == null) {
			return true;
		} else {
			User newUser = object.getUser();

			if(user == null || newUser == null) {
				throw new UnspecifiedUserException();
			} else if (user.equals(newUser)){
				return true;
			} else {
				throw new WrongUserableUserException(user, newUser);
			}
		}
	}

}
